package com.zhugang.week04;

/**
 * @program algorithms
 * @description: mergeTwoLists
 * @author: chanzhugang
 * @create: 2022/06/24 00:25
 */
public class MergeTwoLists {

    /**
     * 合并两个排序链表
     *
     * @param l1
     * @param l2
     * @return
     */
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        // 遍历两个链表，比较节点值大小，小的节点追加到新链表尾部
        ListNode newNode = new ListNode();
        ListNode tail = newNode;
        ListNode p1 = l1;
        ListNode p2 = l2;
        while (p1 != null && p2 != null) {
            // 尾插法
            if (p1.val <= p2.val) {
                tail.next = p1;
                tail = p1;
                p1 = p1.next;
            } else {
                tail.next = p2;
                tail = p2;
                p2 = p2.next;
            }
        }
        if (p1 != null) {
            tail.next = p1;
        }
        if (p2 != null) {
            tail.next = p2;
        }
        return newNode.next;
    }

    public class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
        }

        public ListNode() {

        }
    }
}